import { LoadingOutlined } from "@ant-design/icons";
import { ActionType } from "@ant-design/pro-components";
import { Button, Divider, Modal, Spin, Upload, message } from "antd";
import { read, utils } from 'xlsx';
import ExportJsonExcel from 'js-export-excel';
import { useEffect, useState } from "react";
import { chronic_diseases_patient_list, volume_license_chronic_diseases } from "@/services/patient";

interface Iprops {
    isShowAuthorizedChronicDiseaseModal: (show: boolean) => void;
    authorizedChronicDisease: boolean;
    actionRef: React.MutableRefObject<ActionType | undefined>;
}

const AuthorizedChronicDisease = (props: Iprops) => {
    const { isShowAuthorizedChronicDiseaseModal, authorizedChronicDisease, actionRef } = props

    // 存储上传成功状态
    const [flag, setFlag] = useState(false)
    // 存储上传成功条数
    const [success_count, setSuccess_count] = useState(0)
    // 存储上传失败条数
    const [failed_count, setFailed_count] = useState(0)
    // 存储上传失败数据
    const [failed_data, setFailed_data] = useState([])
    // 控制loading状态
    const [isShowLoading, setIsShowLoading] = useState(false)
    // 存储可授权慢病的全部患者列表
    const [patient_list, setPatient_list] = useState<any>([])

    // 获取可授权慢病的全部患者列表
    useEffect(() => {
        const getData = async () => {
            let res: any = await chronic_diseases_patient_list()
            console.log('可授权慢病的全部患者列表', res);
            if (res.code == 200) {
                res.data.map((item:any)=>{
                    item.sex==0?item.sex='未知':item.sex==1?item.sex='男':item.sex='女'
                })
                setPatient_list(res.data)
            }
        }
        getData()
    }, [])

    // 下载未授权慢病患者信息模板
    const downloadPatientList = (tableName: string = '未授权慢病患者信息模板') => {
        const XLSX = require("xlsx");
        const XLSXStyle = require("xlsx-style");
        // 创建工作簿
        const workbook = XLSX.utils.book_new();
        // 自定义表头
        let headers = {
            id: '*患者id',
            phone: '*手机号',
            username: '*患者姓名',
            sex: '*性别',
            id_card: '*身份证号',
            chronic_diseases_manage: '*慢病分类',
            doctor_name: '*医生',
            content: '慢病分类选择请填写数值：1或2或3 1：高血压，2：糖尿病，3：高血压，糖尿病'
        }
        patient_list.unshift(headers)
        const worksheet = XLSX.utils.json_to_sheet(patient_list, {
            header: ['id', 'phone', 'username', 'sex', 'id_card', 'chronic_diseases_manage', 'doctor_name', 'content'],
            skipHeader: true
        });
        // 设置列宽
        worksheet['!cols'] = [{ wch: 10 }, { wch: 15 }, { wch: 10 }, { wch: 5 }, { wch: 25 }, { wch: 10 }, { wch: 10 }, { wch: 32 }]
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1")
        let arr=[{row:'A1',text:"*患者id"},{row:'B1',text:'*手机号'},{row:'C1',text:'*患者姓名'},{row:'D1',text:'*性别'},{row:'E1',text:'*身份证号'},{row:'F1',text:'*慢病分类'},{row:'G1',text:'*医生'},{row:'H1',text:'慢病分类选择请填写数值：1或2或3 1：高血压，2：糖尿病，3：高血压，糖尿病'}]
        // 设置某个单元格样式
        arr.map((item:any)=>{
             worksheet[item.row] = {
            t: 's',
            v: item.text,
            s: {
                font: {
                    sz:9,
                    color: { rgb: 'ff0000' }
                },
                alignment:{
                    wrapText:true,
                    indent:1,
                    horizontal:'centerContinuous',
                    vertical:'center'
                }
            }
        }
        })
       
        // 使用xlsx-style写入文件方式，使得自定义样式生效
        const tempDown = new Blob([
            s2ab(
                XLSXStyle.write(workbook, {
                    bookType: 'xlsx',
                    bookSST: true,
                    type: 'binary',
                    cellStyles: true
                })
            )
        ])
        // 导出excel文件
        downExcel(tempDown, tableName + '.xlsx')

    }
    // 自定义下载文件方法
    const downExcel = (obj: any, fileName: string) => {
        const a_node = document.createElement('a');
        a_node.download = fileName;
        if ('msSaveOrOpenBlob' in navigator) {
            window.navigator.msSaveOrOpenBlob(obj, fileName);
        } else {
            a_node.href = URL.createObjectURL(obj)
        }
        a_node.click();
        setTimeout(() => {
            URL.revokeObjectURL(obj)
        }, 2000)
    }
    // 文件流转换
    const s2ab:any = (s: any) => {
        if (typeof ArrayBuffer !== 'undefined') {
            const buf = new ArrayBuffer(s.length);
            const view = new Uint8Array(buf);
            for (let i = 0; i != s.length; i++) {
                view[i] = s.charCodeAt(i) & 0xff;
            }
            return buf;
        } else {
            const buf = new Array(s.length);
            for (let i = 0; i != s.length; i++) {
                buf[i] = s.charCodeAt(i) & 0xff;
            }
            return buf
        }
    }

    // 解析上传的excel文件 读取数据
    const analyseExcelToJson = (file: any) => {
        return new Promise((resolve, reject) => {
            // console.log(file);
            if (file.originFileObj instanceof File) {
                const reader = new FileReader();
                reader.onloadend = (progressEvent: any) => {
                    const data = new Uint8Array(progressEvent.target.result);
                    const options: any = { type: 'array' };
                    const workbook = read(data, options);
                    const sheetName: any = workbook.SheetNames;
                    const sheet = workbook.Sheets[sheetName[0]];
                    const jsonData = utils.sheet_to_json(sheet, { header: 1, defval: '', blankrows: false })
                    resolve(jsonData);
                };
                reader.readAsArrayBuffer(file.originFileObj);
            } else {
                reject(new Error('入参不是 File 类型'));
            }
        });
    };
    //  批量导入
    const uploadprops = {
        name: 'file',
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        showUploadList: false,
        onChange(info: any) {
            if (info.file.status !== 'uploading') {
                setIsShowLoading(true)
                setFlag(false)
                analyseExcelToJson(info.file).then(async (result: any) => {
                    // console.log('表格数据', result.slice(1))
                    let res: any = [];
                    const newArr = result.slice(1)
                    console.log('newArr',newArr);
                    
                    const newPhoneListLength = new Set(newArr.map((item: any) => item[1])).size;
                    const newIdCardListLength = new Set(newArr.map((item: any) => item[4])).size;
                    // console.log('newPhoneListLength', newPhoneListLength);
                    // console.log('newIdCardListLength', newIdCardListLength);
                    //判断 result 中 必填字段是否为空
                    if (newArr.some((item: any) => item[0].toString().trim() === '' || item[1].toString().trim() === '' || item[2].toString().trim() === '' || item[3].toString().trim() === '' || item[4].toString().trim() === '' || item[5].toString().trim() === '' || item[6].toString().trim() === '')) {
                        message.error('上传失败，表格内有必填项为空！')
                        setIsShowLoading(false)
                        return;
                    }
                    //判断 result 中 是否有重复手机号
                    //判断 result 中 是否有重复身份证号
                    if (newArr.length != newPhoneListLength || newArr.length != newIdCardListLength) {
                        message.error('上传失败，表格内数据有手机号或身份证号重复！')
                        setIsShowLoading(false)
                        return;
                    }
                    newArr.map((item: any) => res.push({ 'id': item[0], 'doctor_name': item[6].toString(), 'type': item[5] }))
                    console.log('ressssssss', res);
                    let params: any = await volume_license_chronic_diseases({ patient_list: JSON.stringify(res) })
                    if (params.code == 200) {
                        message.success('上传成功！')
                        setIsShowLoading(false)
                        setFlag(true)
                        setSuccess_count(params.data.success_count)
                        setFailed_count(params.data.failed_count)
                        setFailed_data(params.data.failed)
                    } else {
                        message.error(params.msg)
                        setIsShowLoading(false)
                    }
                });
            }
        }
    }

    // 下载上传失败数据
    const downloadFailedData = (tableName: string = '授权失败数据') => {
        // 存储表格数据
        let tableData: any = [];
        // 添加标题行
        let title = ['患者id', '手机号', '患者姓名', '性别', '身份证号', '慢病分类', '医生', '失败原因'];
        failed_data.map((item: { phone: string; name: string; id_card: string; id: number; sex: number; chronic_diseases_manage: number; doctor_name: string; failed_reason: string; }) => {
            let objRow = {
                '患者id': item.id,
                '手机号': item.phone,
                '患者姓名': item.name,
                '性别': item.sex,
                '身份证号': item.id_card,
                '慢病分类': item.chronic_diseases_manage,
                '医生': item.doctor_name,
                '失败原因': item.failed_reason
            }
            tableData.push(objRow)
        })

        var option = {
            fileName: tableName,
            datas: [
                {
                    sheetHeader: title,//表头数据
                    sheetData: tableData,//数据源
                    sheetName: 'sheet',
                    sheetFilter: title,
                    columnWidths: ['3', '5', '4', '3', '10', '5', '5', '25'],
                }
            ]
        };
        let toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
    }
    return (
        <Modal
            title="授权慢病"
            open={authorizedChronicDisease}
            onCancel={() => isShowAuthorizedChronicDiseaseModal(false)}
            width={500}
            destroyOnClose={true}
            footer={null}
        >
            <Divider />
            <div style={{ cursor: 'pointer' }} onClick={() => downloadPatientList()}>1、下载<span style={{ color: '#1677FF' }}>《未授权慢病患者信息》</span>，维护慢病类型及负责医生的信息</div>
            <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', }}>2、上传填写好的未授权慢病患者信息模板 <div style={{ margin: '0 10px 0 10px' }}><Upload {...uploadprops}>
                <Button>上传</Button>
            </Upload></div> {isShowLoading ? <Spin indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />} /> : ''}</div>
            {flag ? <div style={{ marginTop: "20px", display: 'flex' }}>授权结果：成功授权{success_count}条数据，{failed_count}条失败 {failed_count > 0 ? <div style={{ color: '#1677FF', cursor: 'pointer', marginLeft: '20px' }} onClick={() => downloadFailedData()}>下载失败数据</div> : ""}</div> : ""}
        </Modal>
    )
}
export default AuthorizedChronicDisease